package cn.tedu.lianxi1;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Serve2 {
    public static void main(String[] args) {

        try{
            //1.创建ServerSocket类型的对象，并提供端口号
            ServerSocket ss = new ServerSocket(8888);
            //2.等待客户端的连接请求，使用accept()方法，保持阻塞状态
            System.out.println("等待客户端的连接请求...");
            Socket s = ss.accept();
            System.out.println("客户端连接成功！");
            //3.使用输入输出流进行通信
            /*
            //服务器接收客户端发来的"hello"并打印
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(s.getInputStream()));
            String str = br.readLine();
            System.out.println(str); // hello
            //向客户端回发消息“I received!”
            PrintStream ps = new PrintStream(s.getOutputStream());
            ps.println("I received!");
            */
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(s.getInputStream()));
            PrintStream ps = new PrintStream(s.getOutputStream());

            //编程实现服务器可以不断地客户端进行通信
            while(true){
                //服务器接收客户端发来的消息并打印
                String str = br.readLine();
                //当客户端发来"bye"时，结束循环
                if("bye".equalsIgnoreCase(str)) break;
                System.out.println("张三说：" + str);
                //向客户端回发消息“I received!”
                System.out.println("请输入要发送的内容：");
                String b=new Scanner(System.in).nextLine();
                ps.println(b);
                if("bye".equalsIgnoreCase(b)) break;
            }
            //4.关闭相关的套接字
            ps.close();
            br.close();
            s.close();
            ss.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}

